<template>
  <div class="container">

    <el-card class="table-container">
      <div style="margin: 0 10px 20px 10px">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="用户名" prop="userName">
            <el-col :span="22">
              <el-input v-model="searchForm.realName" :rows="5" clearable type="text" placeholder="请输入用户名" />
            </el-col>
          </el-form-item>
          <el-form-item label="手机号" prop="email" label-width="80px">
            <el-col :span="22">
              <el-input v-model="searchForm.email" :rows="5" clearable type="text" placeholder="请输入电子邮件" />
            </el-col>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :loading="queryLoading" @click="handleQuery">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="addUserDialog = true">新增用户</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="success" plain @click="handleExportExcel">导入用户</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" plain @click="handleTemplateExcel">导出用户Excel模板</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table v-loading="queryLoading" :data="tableData.list" :header-row-class-name="'table-head-th'" row-key="id"
        fit highlight-current-row>

        <el-table-column key="userName" show-overflow-tooltip prop="userName" label="SmapUid" />
        <el-table-column key="realName" show-overflow-tooltip prop="realName" label="真实姓名" />
        <el-table-column key="email" show-overflow-tooltip prop="email" label="角色" >
          <template slot-scope="scope">
            {{ scope.row.roleName[0] }}
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="yytname" label="营业厅">
          <template slot-scope="scope">
            {{ scope.row.yytname ? scope.row.yytname : '超级管理员' }}
          </template>
        </el-table-column>
        <el-table-column key="state" show-overflow-tooltip prop="state" label="状态">
          <template slot-scope="scope">
            <el-tag :type="scope.row.state | statusFilter">
              <div v-if="scope.row.state === true">激活</div>
              <div v-else>删除</div>
            </el-tag>
          </template>
        </el-table-column>
        <!-- 表格操作列 -->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button-group>
              <el-button size="mini" title="权限管理" type="primary" @click="handlePerm(scope.$index, scope.row)">
                <i class="fa fa-pencil" />
              </el-button>
              <el-button size="mini" title="删除" type="danger" @click="handleDel(scope.row)">
                <i class="fa fa-trash-o" />
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页信息 -->
      <div class="pagination-container">
        <el-pagination :current-page="pageNum" :total="tableData.total" background
          layout="total, prev, pager, next, jumper" @current-change="handlePageChange"
          @size-change="handleSizeChange" />
      </div>
    </el-card>

    <!-- 详情弹窗 -->
    <el-dialog :visible.sync="dialogFormVisible" width="30%" :title="dialogType == 'see' ? '查看详情' : '编辑'">
      <el-form :model="dialogForm">
        <el-form-item key="id" label="编号" label-width="100px">
          <el-col :span="22">
            <el-input v-model="dialogForm['id']" :disabled="dialogType == 'see'" :rows="5" auto-complete="off" />
          </el-col>
        </el-form-item>
        <el-form-item key="userName" label="SmapUid" label-width="100px">
          <el-col :span="22">
            <el-input v-model="dialogForm['userName']" :disabled="dialogType == 'see'" :rows="5" auto-complete="off" />
          </el-col>
        </el-form-item>
        <el-form-item key="email" label="电子邮件" label-width="100px">
          <el-col :span="22">
            <el-input v-model="dialogForm['email']" :disabled="dialogType == 'see'" :rows="5" auto-complete="off" />
          </el-col>
        </el-form-item>
        <el-form-item key="password" label="密码" label-width="100px">
          <el-col :span="22">
            <el-input v-model="dialogForm['password']" :disabled="dialogType == 'see'" :rows="5" auto-complete="off" />
          </el-col>
        </el-form-item>
        <el-form-item key="salt" label="盐" label-width="100px">
          <el-col :span="22">
            <el-input v-model="dialogForm['salt']" :disabled="dialogType == 'see'" :rows="5" auto-complete="off" />
          </el-col>
        </el-form-item>
        <el-form-item key="token" label="用户令牌" label-width="100px">
          <el-col :span="22">
            <el-input v-model="dialogForm['token']" :disabled="dialogType == 'see'" :rows="5" auto-complete="off" />
          </el-col>
        </el-form-item>
        <el-form-item key="avatar" label="头像" label-width="100px">
          <el-col :span="22">
            <el-input v-model="dialogForm['avatar']" :disabled="dialogType == 'see'" :rows="5" auto-complete="off" />
          </el-col>
        </el-form-item>
        <el-form-item key="introduction" label="介绍" label-width="100px">
          <el-col :span="22">
            <el-input v-model="dialogForm['introduction']" :disabled="dialogType == 'see'" :rows="5"
              auto-complete="off" />
          </el-col>
        </el-form-item>
        <el-form-item key="state" label="状态" label-width="100px">
          <el-col :span="22">
            <el-input v-model="dialogForm['state']" :disabled="dialogType == 'see'" :rows="5" auto-complete="off" />
          </el-col>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="SubmitCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog :visible.sync="PermFormVisible" width="40%" title="权限管理">
      <el-form ref="PermForm" :model="PermForm" :rules="formRules">
        <el-form-item key="userName" label="用户名" label-width="100px">
          <el-col :span="22">
            <el-input v-model="PermForm['userName']" :rows="5" :disabled="true" auto-complete="off" />
          </el-col>
        </el-form-item>
        <el-form-item label="用户角色" prop="checkedPart" label-width="100px">
          <el-col :span="22" class="checkbox-group">
            <!-- <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate"
              @change="handleCheckAllChange">全选</el-checkbox> -->
            <el-radio-group v-model="PermForm['checkedPart']" size="mini" @change="handlecheckedPartChange">
              <el-radio v-for="role in rolesOptions" v-if="role['role'] !== 'superadmin'" :key="role['id']"
                :label="role['role']" name="checkedPart" class="checkboxContent" border>{{ role['description']
                }}</el-radio>
            </el-radio-group>
          </el-col>
        </el-form-item>
        <!-- <el-form-item prop="email" label="手机号" label-width="100px">
          <el-col :span="22">
            <el-input v-model="PermForm.email" placeholder="请输入手机号" name="email" type="text" auto-complete="on" />
          </el-col>
        </el-form-item> -->
        <el-form-item prop="deptId" label="部门" label-width="100px" v-if="PermForm['checkedPart'] != 'super_admin'">
          <el-col :span="22">
            <el-select v-model="PermForm.deptId" placeholder="请选择" ref="selectTree1" style="width: 100%;">
              <el-option :key="treeForm.id" :value="treeForm.id" :label="treeForm.label" hidden />
              <el-tree :data="DepartmentList" :props="defaultProps" node-key="id" accordion highlight-current
                @node-click="handleNodeClick1" />
            </el-select>
          </el-col>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="SubmitCancel">取 消</el-button>
        <el-button type="primary" @click="SubmitPerForm">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="addUserDialog" width="30%" title="新建用户">
      <el-form ref="registerForm" :model="registerForm" :rules="registerRules" class="register-form" label-width="100px"
        label-position="left">
        <div class="text item">
          <el-form-item prop="username" label="SmapUid">
            <el-col :span="22">
              <el-input v-model="registerForm.username" placeholder="请输入SmapUid 如lizhitao@sn.cmcc" name="username"
                type="text" auto-complete="on" />
            </el-col>
          </el-form-item>
          <el-form-item prop="realName" label="真实姓名">
            <el-col :span="22">
              <el-input v-model="registerForm.realName" placeholder="请输入真实姓名" name="realName" type="text"
                auto-complete="on" />
            </el-col>
          </el-form-item>

          <el-form-item prop="roleIds" label="角色">
            <el-col :span="22">
              <el-select v-model="registerForm.roleIds" @change="handleChange" placeholder="请选择角色" style="width: 100%;">
                <el-option v-for="item in rolesOptions" :key="item.role" :label="item.description" :value="item.id" />
              </el-select>
            </el-col>
          </el-form-item>
          <el-form-item prop="deptId" label="部门">
            <el-col :span="22">
              <el-select v-model="registerForm.deptId" placeholder="请选择" ref="selectTree" style="width: 100%;">
                <el-option :key="treeForm.id" :value="treeForm.id" :label="treeForm.label" hidden />
                <el-tree :data="treeList" :props="defaultProps" node-key="id" accordion highlight-current
                  @node-click="handleNodeClick" />
              </el-select>
            </el-col>
          </el-form-item>
          <div class="button-container" style="text-align: center">
            <el-button :loading="loading" type="primary" @click.native.prevent="handleRegister">注册</el-button>
          </div>
        </div>
      </el-form>
    </el-dialog>
    <el-dialog :visible.sync="importingDialog" width="30%" title="用户批量导入">
      <div style="width: 100%;display: flex;justify-content: center;">
        <el-upload drag :action="action" ref="uploadFile" accept=".xlsx, .xls" :headers="headers" :limit="1"
          :before-upload="beforeAvatarUpload" :on-success="handleAvatarSuccess" :on-error="handleAvatarError">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">只能上传xlsx文件</div>
        </el-upload>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import { Message } from 'element-ui'
import SysUserApi from '../api/sysUser'
import SysRoleApi from '@/modules/sys_role/api/sysRole'
import UserRoleRelApi from '@/modules/sys_role/api/userRoleRel'
import { validateAlphabets, validEmail, validPhone } from '@/utils/validate'
import RegisterApi from '@/modules/register/api/register'
import sha256 from 'js-sha256'
import SysDepartmentApi from "@/modules/department/api/department";
import URL from '@/api/api'
import { getToken } from '@/utils/auth'
export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        true: 'success',
        false: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validateAlphabets(value)) {
        callback(new Error('请输入正确的用户名'))
      } else {
        callback()
      }
    }
    const validateUserEmail = (rule, value, callback) => {
      if (!validPhone(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('输入的密码不少于6位'))
      } else {
        callback()
      }
    }
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.registerForm.password) {
        callback(new Error('两次输入密码不一样'))
      } else {
        callback()
      }
    }
    return {
      checkAll: false,
      isIndeterminate: true,
      queryLoading: false,
      /* 搜索面板数据*/
      searchConfig: [],
      /* 搜索请求数据*/
      searchForm: {},
      pageSize: 10,
      pageNum: 1,
      /* 表格面板数据*/
      tableConfig: [],
      // 表格数据
      tableData: {
        results: []
      },
      dialogForm: {},
      PermForm: {
        id: '',
        userName: '',
        checkedPart: [],
        email: "",
        deptId: ""
      },
      dialogType: 'see',
      dialogFormVisible: false,
      PermFormVisible: false,
      addUserDialog: false,
      formLabelWidth: '120px',
      rolesOptions: [],
      passwordType: 'password',
      registerForm: {
        username: '',
        roleIds: '',
        password: '123456',
        confirmPassword: '123456',
        email: '',
        deptId: ''
      },
      registerRules: {
        username: [{ required: true, trigger: 'blur', message: '请输入' }],
        realName: [{ required: true, trigger: 'blur', message: '请输入真实姓名' }],
        roleIds: [{ required: true, trigger: 'change', message: '请选择角色' }],
        deptId: [{ required: true, trigger: 'change', message: '请选择部门' }],
      },
      // 角色列表
      rolesList: [],
      loading: false,
      showDialog: false,
      redirect: undefined,
      capsTooltip: false,
      formRules: {
        checkedPart: [{ required: true, message: '至少选择一个部分', trigger: 'change' }],
        email: [{ required: true, trigger: 'blur', validator: validateUserEmail }],
        deptId: [{ required: true, trigger: 'change', message: '请选择部门' }],
      },
      DepartmentList: [],
      treeList: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      treeForm: {
        id: '',
        value: ''
      },
      importingDialog: false,
      action: URL + "/user/batchRegister",
      headers: {
        Authorization: getToken(),
      },
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    // 页面初始化
    init() {
      this.getAllRole()
      this.getDepartment()
      this.query()
    },
    checkCapslock({ shiftKey, key } = {}) {
      if (key && key.length === 1) {
        if (shiftKey && (key >= 'a' && key <= 'z') || !shiftKey && (key >= 'A' && key <= 'Z')) {
          this.capsTooltip = true
        } else {
          this.capsTooltip = false
        }
      }
      if (key === 'CapsLock' && this.capsTooltip === true) {
        this.capsTooltip = false
      }
    },
    handleChange() {
      this.treeForm={
        id:undefined,
        value:undefined,
        label:undefined
      }
      this.registerForm.deptId=undefined
      if (this.registerForm.roleIds == 1) {
        this.treeList = [{ id: 0, name: "超级管理员",label:"超级管理员" }]
      }else{
        this.treeList=this.DepartmentList
      }
    },
    handleQuery() {
      this.query()
    },
    handleCheckAllChange(val) {
      this.PermForm.checkedPart = val ? this.rolesList : []
      this.isIndeterminate = false
    },
    handlecheckedPartChange(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.rolesList.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.rolesList.length
    },
    getDepartment() {
      return new Promise((resolve, reject) => {
        this.queryLoading = true;
        const param = Object.assign({}, this.searchForm);

        SysDepartmentApi.queryTree(param)
          .then((response) => {
            const data = response.data;
            if (data.code === 200) {

              const data = response.data.data;
              this.DepartmentList = [...data];

            } else {
              Message.error(data.message);
              reject();
            }
          })
          .catch((error) => {
            if (error.message !== "") {
              //Message.error(error.message)
            }
            reject(error);
          });
      });
    },
    getThisUserRole(id) {
      return new Promise((resolve, reject) => {
        SysRoleApi
          .queryUserRole(id)
          .then(response => {
            const data = response.data
            if (data.code === 200) {
              const data = response.data.data
              this.PermForm.checkedPart = data[0]
            } else {
              Message.error(data.message)
              reject()
            }
          })
          .catch(error => {
            // Message.error(error.message || error || "未知错误")

            reject(error)
          })
      })
    },
    getAllRole() {
      return new Promise((resolve, reject) => {
        SysRoleApi
          .query()
          .then(response => {
            const data = response.data
            if (data.code === 200) {
              const data = response.data.data
              this.rolesOptions = data.list
              for (var role in data.list) {
                this.rolesList.push(data.list[role].role)
              }
            } else {
              Message.error(data.message)
              reject()
            }
          })
          .catch(error => {
            // Message.error(error.message || error || "未知错误")
            reject(error)
          })
      })
    },
    query() {
      this.queryLoading = true
      return new Promise((resolve, reject) => {
        const param = Object.assign({}, this.searchForm)
        SysUserApi
          .queryByCond(param, this.pageSize, this.pageNum)
          .then(response => {
            const data = response.data
            this.queryLoading = false
            if (data.code === 200) {
              const data = response.data.data
              this.tableData = data
            } else {
              Message.error(data.message)
              reject()
            }
          })
          .catch(error => {
            this.queryLoading = false
            reject(error)
          })
      })
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
    },
    handleRegister() {
      this.$refs.registerForm.validate(valid => {
        if (valid) {
          this.loading = true
          const params = Object.assign({}, this.registerForm)
          params.password = sha256(this.registerForm.password)
          if(params.deptId==0){
            params.deptId=null
          }
          return new Promise((resolve, reject) => {

            RegisterApi
              .register({...params,roleIds:[params.roleIds]})
              .then(response => {
                const data = response.data
                this.loading = false
                if (data.code === 200) {
                  Message.success('注册成功..')
                  this.addUserDialog = false
                  this.query()
                  this.$refs.registerForm.resetFields()
                } else {
                  Message.error(data.message)
                  return
                }
                resolve(data)
              })
              .catch(error => {
                this.loading = false
                // Message.error(error.message || error || "未知错误")
                reject(error)
              })
          })
        } else {

          return false
        }
      })
    },
    handleSee(index, row) {
      this.dialogType = 'see'
      this.dialogForm = row
      this.dialogFormVisible = true
    },
    handleEdit(index, row) {
      this.dialogType = 'edit'
      this.dialogForm = row
      this.dialogFormVisible = true
    },
    handlePerm(index, row) {
      this.PermForm.id = row.id
      this.PermForm.userName = row.userName
      this.PermForm.email = row.email
      this.PermForm.deptId = row.yytid
      this.treeForm = {
        id: row.yytid,
        value: row.yytname,
        label: row.yytname
      },
        this.getThisUserRole(row.id)
      this.PermFormVisible = true
    },

    SubmitCancel() {
      this.dialogFormVisible = false
      this.PermFormVisible = false
      this.query()
    },
    // 处理翻页事件
    handlePageChange(currentPage) {
      this.pageNum = currentPage
      this.query()
    },
    // 处理页面总条数事件
    handleSizeChange(val) {

      this.pageSize = val
      this.query()
    },
    handleNodeClick(data) {

      this.treeForm = {
        id: data.id,
        value: data.name,
        label: data.name
      }
      this.registerForm.deptId = data.id
      // 使 input 失去焦点，并隐藏下拉框
      this.$refs.selectTree.blur()
    },
    handleNodeClick1(data) {
      this.treeForm = {
        id: data.id,
        value: data.name,
        label: data.name
      }
      this.PermForm.deptId = data.id
      // 使 input 失去焦点，并隐藏下拉框
      this.$refs.selectTree1.blur()
    },
    handleDel(row) {
      this.$confirm('确定删除吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const param = Object.assign({}, row)
          SysUserApi
            .delete(param)
            .then(response => {
              const data = response.data
              if (data.code === 200) {
                this.$message({
                  message: '删除成功',
                  type: 'success'
                })
                this.handleQuery()
              } else {
                Message.error(data.message)
              }
            })
            .catch(error => {
              // console.log(error)
              // Message.error(error.message || error || "未知错误")
            })
        })
        .catch(() => {
        })
    },
    SubmitPerForm(row) {
      this.loading = true
      this.$refs['PermForm'].validate(valid => {
        if (valid) {
          const params = Object.assign({}, this.PermForm)

          if(params.checkedPart=='super_admin'){
            params.deptId=null
          }
          return new Promise((resolve, reject) => {
            UserRoleRelApi
              .updateUserRoleRel({ ...params, checkedPart: [params.checkedPart] })
              .then(response => {
                this.loading = false
                const data = response.data
                if (data.code === 200) {
                  this.$message({
                    message: '修改成功',
                    type: 'success'
                  })
                  this.PermFormVisible = false
                  this.loading = false
                  this.query()
                } else {
                  Message.error(data.message)
                  reject()
                }
              })
              .catch(error => {
                this.loading = false
                // Message.error(error.message || error || "未知错误")
                reject(error)
              })
          })
        } else {
          this.loading = false
          return false
        }
      })
    },
    handleTemplateExcel() {

      SysUserApi.daoDownload().then(res => {
        console.log(res.data, 99999)
        if (res.data) {
          const elink = document.createElement('a');
          elink.download = `用户导入模板.xlsx`;
          elink.style.display = 'none';
          elink.href = window.URL.createObjectURL(res.data);
          document.body.appendChild(elink);
          elink.click();
          document.body.removeChild(elink);
        } else {
          this.$message.error('导出异常请联系管理员');
        }
      })

    },
    handleExportExcel() {
      this.importingDialog = true
      this.$refs.uploadFile.clearFiles()
    },
    beforeAvatarUpload(file) {
      const extension = file.name.split(".")[1] === "xls";
      const extension2 = file.name.split(".")[1] === "xlsx";
      if (!extension && !extension2) {
        this.$message.error("上传文件只能是 xls、xlsx 格式!");
        return false;
      }
    },
    handleAvatarSuccess(resp) {
      if (resp.code == 200) {
        Message.success("导入成功")
        this.query()
      } else {
        Message.error("导入失败")
      }
      this.importingDialog = false
    },
    handleAvatarError() {
      Message.error("文件上传失败")

    }
  }
}
</script>
<style>
.container {
  margin: 10px;
}

.table-container {
  margin-top: 0px;
}

.pagination-container {
  margin-top: 30px;
  text-align: right;
}

.show-pwd {
  position: absolute;
  right: 10px;
  top: 7px;
  font-size: 16px;
  color: #889aa4;
  cursor: pointer;
  user-select: none;
}
</style>
